import Taro from '@tarojs/taro'
import React, { Component } from 'react'
import { limit } from '@pier88health/p8h-common'
import { convertPx, getWebRealPx } from '@UTILS/common'
import { NoContentEmpty } from '@COMPONENTS/Empty'

const { debounce } = limit

export default class ListWeb extends Component {
  static defaultProps = {
    style: {},
    listHeaderHeight: 0
  }

  constructor(props) {
    super(props);
    this.onEndReached = debounce(this.onEndReached, 500)
    this.state = {
      height: 500
    }
  }

  componentDidMount() {
    const { listHeaderHeight } = this.props
    Taro.getSystemInfo({
      success: res => {
        this.setState({
          height: res.windowHeight - getWebRealPx(listHeaderHeight)
        })
      }
    })
  }

  componentDidUpdate(prevProps) {
    const { listHeaderHeight } = this.props
    if (prevProps.listHeaderHeight !== listHeaderHeight) {
      Taro.getSystemInfo({
        success: res => {
          this.setState({
            height: res.windowHeight - getWebRealPx(listHeaderHeight)
          })
        }
      })
    }
  }

  isScrolling = false

  onEndReached = () => {
    const { onEndReached } = this.props
    if (this.isScrolling || !onEndReached) {
      return
    }
    this.isScrolling = true
    onEndReached()
    this.isScrolling = false
  }

  onScroll = e => {
    const { refreshing, isLoading } = this.props
    if (refreshing || isLoading) return
    const { target } = e.nativeEvent
    const { clientHeight } = target;
    if (target.scrollTop + clientHeight > target.scrollHeight - 100) {
      this.onEndReached()
    }
  }

  render() {
    const {
      children, refreshing, backgroundColor, style
    } = this.props
    const { height } = this.state
    const isEmpty = Array.isArray(children) && (children.length === 0 && !refreshing)
    return (
      // eslint-disable-next-line react/forbid-elements
      <div
        onScroll={this.onScroll}
        className="list"
        style={{
          height: convertPx(height), overflowX: 'auto', backgroundColor, ...style
        }}
      >
        {isEmpty ? <NoContentEmpty /> : children}
      </div>
    )
  }
}
